/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import Model.Bean.Inmuebles;
import Model.Bean.PagoRenta;
import Model.Bean.Rendamientos;
import Model.Servicios.InmuebleSrv;
import Model.Servicios.PagoRentaSrv;
import Model.Servicios.RendamientoSrv;
import Util.Constantes;
import Util.Fecha;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import sun.security.jca.GetInstance;

/**
 *
 * @author sixviv
 */
public class rentarInmueble extends HttpServlet {
    private Rendamientos rendamiento = new Rendamientos();
    private static final String TMP_DIR_PATH = "/tmp/";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH ="/files";
    private File destinationDir;
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    @Override
    public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if(!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		if(!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
		}

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/inmuebles");
        PrintWriter out = response.getWriter();
        RendamientoSrv rSrv = new RendamientoSrv();
        InmuebleSrv iSrv = new InmuebleSrv();
        try {
            Inmuebles inmueble = (Inmuebles) request.getSession().getAttribute("inmueble");
            request.getSession().removeAttribute("inmueble");
            inmueble.setDisponibilidad(Constantes.FALSO);
                       
            rendamiento.setInmuebles(inmueble);
            setRendamiento(request);
            
            rSrv.guardar(rendamiento);
//            iSrv.actualizar(inmueble);
            rd.forward(request, response);
        } finally { 
            out.close();
        }
    }

    private void setRendamiento(HttpServletRequest request){
        DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if(!item.isFormField() && !item.getString().isEmpty()) {
                                    File file = new File(destinationDir,item.getName());
                                    item.write(file);
                                    if(item.getFieldName().contentEquals("contratoFile")){
                                        rendamiento.setContratoPath(file.getName());
                                    }
                                    if(item.getFieldName().contentEquals("depositoFile")){
                                        rendamiento.setDepositoPath(file.getName());
                                    }
                                    if(item.getFieldName().contentEquals("ifeFile")){
                                        rendamiento.setIfePath(file.getName());
                                    }
                                    if(item.getFieldName().contentEquals("facturaFile")){
                                        rendamiento.setFacturaPath(file.getName());
                                        rendamiento.setFactura(Constantes.VERDADERO);
                                    }else{
                                        rendamiento.setFactura(Constantes.FALSO);
                                    }
                                    if(item.getFieldName().contentEquals("contratoLuzPath")){
                                        rendamiento.setContratoLuzPath(file.getName());
                                    }
                                    if(item.getFieldName().contentEquals("contratoAguaPath")){
                                        rendamiento.setContratoAguaPath(file.getName());
                                    }
				}else{
                                    String pattern = "dd/MM/yyyy";
                                    SimpleDateFormat format = new SimpleDateFormat(pattern);
                                    if(item.getFieldName().contentEquals("fechaAgua")){
                                        rendamiento.setFechaAgua(format.parse(item.getString()));
                                    }
                                    if(item.getFieldName().contentEquals("fechaLuz")){
                                        rendamiento.setFechaLuz(format.parse(item.getString()));
                                    }
                                    if(item.getFieldName().contentEquals("inicioContrato")){
                                        rendamiento.setFechaContrato(format.parse(item.getString()));
                                    }
                                    if(item.getFieldName().contentEquals("duracion")){
                                        rendamiento.setDuracion(Integer.valueOf(item.getString()));
                                    }
                                    if(item.getFieldName().contentEquals("arrendador")){
                                        rendamiento.setArrendador(item.getString());
                                    }
                                    if(item.getFieldName().contentEquals("importeDeposito")){
                                        rendamiento.setImporte(Double.valueOf(item.getString()));
                                    }
                                    if(item.getFieldName().contentEquals("importeRenta")){
                                        rendamiento.setImporteRenta(Double.valueOf(item.getString()));
                                    }
                                }
			}
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(rendamiento.getFechaContrato());
                        calendar.add(Calendar.YEAR, rendamiento.getDuracion());
                        rendamiento.setFechaFinalizacion(calendar.getTime());
                        saveDates();
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}

    }

    private void saveDates(){
        PagoRentaSrv prSrv = new PagoRentaSrv();
        PagoRenta pr = new PagoRenta();
        pr.setRendamientos(rendamiento);
        for(int i =1; i<=rendamiento.getDuracion()*12; i++){
            pr.setFechaPago(Fecha.sumarFechasDias(rendamiento.getFechaContrato(),i));
            prSrv.insertar(pr);
        }
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
